package com.xjscrm.server.service.wwgrouptags.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.entity.WwGroupTags;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.dto.wwgrouptags.WwGroupTagsQuery;
import com.xjscrm.server.mapper.WwGroupTagsMapper;
import com.xjscrm.server.service.wwgrouptags.WwGroupTagsSyncService;
import com.xjscrm.server.service.wwgrouptags.WwGroupTagsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 群发任务异步实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class WwGroupTagsSyncServiceImpl implements WwGroupTagsSyncService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WwGroupTagsMapper wwGroupTagsMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private WwGroupTagsService wwGroupTagsService;

    /**
     * 自动打群标签
     *
     * @param merId
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForXxJob")
    @TraceGenerate //注入消息id标签
    public void autoWwGroupTagsSync(@MerId Long merId) {
        //限流key
        String taskLimitKet = "-autoWwGroupTagsSync-taskLimitKey-merId=" + merId;
        Object object = redisTemplate.opsForValue().get(taskLimitKet);
        if (object != null) {
            return;
        }
        //保存限流key
        redisTemplate.opsForValue().set(taskLimitKet, taskLimitKet, 30, TimeUnit.MINUTES);

        log.info("-----处理自动打群标签任务----merId=" + merId);

        try {
            //查询当前所有开启的自动发圈的配置方案
            int now = DateUtil.getTime();

            WwGroupTagsQuery wwGroupTagsQuery = new WwGroupTagsQuery();
            wwGroupTagsQuery.setMerId(merId);

            //查询所有的自动发圈配置记录
            Page<WwGroupTags> page = new Page<>();
            page.setCurrent(1);//只查第一页
            page.setSize(10); //每页查询10个
            page.addOrder(OrderItem.asc("id"));//默认id升序
            Long idStart = 0L;
            List<WwGroupTags> wwGroupTagsList = wwGroupTagsMapper.findByList(page, wwGroupTagsQuery);
            while (wwGroupTagsList != null && wwGroupTagsList.size() > 0) {
                for (WwGroupTags wwGroupTags : wwGroupTagsList) {
                    if (wwGroupTags.getId().longValue() >idStart.longValue()) {
                        idStart = wwGroupTags.getId();
                    }

                    //限流判断
                    String rateLimitKey = "autoWwGroupTagsSync-taskId=" + wwGroupTags.getId();
                    Object rateLimitKeyobject = redisTemplate.opsForValue().get(rateLimitKey);
                    if (rateLimitKeyobject == null) {
                        //保存限流key
                        redisTemplate.opsForValue().set(rateLimitKey, rateLimitKey, 300, TimeUnit.SECONDS);
                    } else {
                        continue;
                    }

                    try {

                        if(Tools.getLong(wwGroupTags.getPid()).longValue() > 0){
                            Integer groupKeyWordSwitch = Tools.getInteger(wwGroupTags.getGroupKeyWordSwitch());
                            Integer upperLimitSwitch = Tools.getInteger(wwGroupTags.getUpperLimitSwitch());
                            if (groupKeyWordSwitch.intValue() == 1 || upperLimitSwitch == 1) {
                                wwGroupTagsService.addWwGroupTags(wwGroupTags);
                            }
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    } finally {
                        //保存成功之后，手动删除限流redisKey
                        redisTemplate.delete(rateLimitKey);
                    }
                }

                wwGroupTagsQuery.setIdStart(idStart);
                wwGroupTagsList = wwGroupTagsMapper.findByList(page, wwGroupTagsQuery);
            }
        } catch (Exception e) {
            log.info(e.getMessage(),e);
        } finally {
            //删除限流key
            redisTemplate.delete(taskLimitKet);
        }
    }


}
